﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;


using System.IO.Ports;
using System.Text.RegularExpressions;
using System.Threading;
using System.Reflection; // 引用这个才能使用Missing字段
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Xml;
using System.Web;
using System.Runtime.InteropServices;
using CCWin;

namespace weiqijiance
{
    public partial class TESTSP : Form
    {
        public string sshebei = "车速";
        public mainform m_mainform;
        public string sdetid;
        /// <summary>
        /// 结果变量
        /// </summary>
        public float fchesu;
        public bool jcxjs = false;//检测线结束标识

        public Thread t1;
        public string xianshineirong;
        public string businessId;
        public string jylsh;
        public string jyjgbh;
        public string jcxdh;
        public string jycs;
        public string jyxm;

        public int xssj = 0;//显示时间
        public int iSPHW=-1;//车速红外
        public int iSPYK;//车速遥控
        public int iSLtdz;//车速信号接在那个通道

        public int iSPJS1;//车速举升
        public int iSPJS2;//车速举升
        public bool cbjd = false;//仪表检定

        public bool scshwyk = false;
        public string revert = "";
        //红外取反
        public bool[] bhongwaiqf = new bool[16] { false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false };//红外是否取反
        //红外定位时间
        public int[] ihongwaidwsj = new int[16] { 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000 };//红外定位时间单位毫秒


        // /声明INI文件的写操作函数 WritePrivateProfileString()
        [DllImport("kernel32")]
        private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);

        //声明INI文件的读操作函数 GetPrivateProfileString()
        [DllImport("kernel32")]
        private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);
        private string sPath = null;


        public 控制流程.flowcrtl flowbass = new 控制流程.flowcrtl();
        public TESTSP(int Width, int Height)
        {
            InitializeComponent();
            panel_Width = Width;
            panel_Height = Height;
            gettongdao();

            x = this.Width;
            y = this.Height;
            setTag(this);
            xinxixianshi.Text = "车速检测";

        }

        public void init()
        {
            iniclass objini = new iniclass();
            string path = "";
            path = System.Windows.Forms.Application.StartupPath + path + "\\安综检仪表配置.ini";
            string path1 = string.Format(@"{0}", path);
            objini.Ini(path1);
            jcxjs = (objini.ReadValue("车速", "检测线结束设备").Trim() == "1") ? true : false;
            int.TryParse(objini.ReadValue("车速", "信息显示时间").Trim(), out xssj);
        }
        public void start()
        {         
            t1 = new Thread(new ThreadStart(Thread1));
            t1.Priority = ThreadPriority.BelowNormal;
            t1.Start();
        }

        #region 控件大小随窗体大小等比例缩放
        private float x;//定义当前窗体的宽度
        private float y;//定义当前窗体的高度
        private void setTag(Control cons)
        {
            foreach (Control con in cons.Controls)
            {
                con.Tag = con.Width + ";" + con.Height + ";" + con.Left + ";" + con.Top + ";" + con.Font.Size;
                if (con.Controls.Count > 0)
                {
                    setTag(con);
                }
            }
        }
        private void setControls(float newx, float newy, Control cons)
        {
            if (newy <= 0)
            {
                newy = 1;
            }
            //遍历窗体中的控件，重新设置控件的值
            foreach (Control con in cons.Controls)
            {
                //获取控件的Tag属性值，并分割后存储字符串数组
                if (con.Tag != null)
                {
                    string[] mytag = con.Tag.ToString().Split(new char[] { ';' });
                    //根据窗体缩放的比例确定控件的值
                    con.Width = Convert.ToInt32(System.Convert.ToSingle(mytag[0]) * newx);//宽度
                    con.Height = Convert.ToInt32(System.Convert.ToSingle(mytag[1]) * newy);//高度
                    con.Left = Convert.ToInt32(System.Convert.ToSingle(mytag[2]) * newx);//左边距
                    con.Top = Convert.ToInt32(System.Convert.ToSingle(mytag[3]) * newy);//顶边距
                    Single currentSize = System.Convert.ToSingle(mytag[4]) * newy;//字体大小
                    con.Font = new Font(con.Font.Name, currentSize, con.Font.Style, con.Font.Unit);
                    if (con.Controls.Count > 0)
                    {
                        setControls(newx, newy, con);
                    }
                }
            }
        }
        #endregion

        //ini文件
        public void Ini(string path)
        {
            this.sPath = path;
        }
        public void Writue(string section, string key, string value)
        {
            // section=配置节，key=键名，value=键值，path=路径
            WritePrivateProfileString(section, key, value, sPath);
        }
        public string ReadValue(string section, string key)
        {
            // 每次从ini中读取多少字节
            System.Text.StringBuilder temp = new System.Text.StringBuilder(255);

            // section=配置节，key=键名，temp=上面，path=路径
            GetPrivateProfileString(section, key, "", temp, 255, sPath);
            return temp.ToString();
        }
        //ini文件


        public void gettongdao()
        {
            string path = "";
            
            path = System.Windows.Forms.Application.StartupPath + path + "\\串口及通道设置.ini";
            string path1 = string.Format(@"{0}", path);
            Ini(path1);
            for (int i = 0; i < 10; i++)
            {
                string sgetname = ReadValue("通道设置", string.Format(@"模拟信号{0}", i + 1));
            }

            scshwyk = ReadValue("通道设置", "车速红外使用遥控").Contains("是") ? true : false;
            for (int i = 0; i < 8; i++)
            {
                string smaichong = ReadValue("通道设置", string.Format(@"速度{0}", i + 1));
                if (smaichong.Contains("车速速度"))
                {
                    iSLtdz = i;
                }
            }

            for (int i = 0; i < 16; i++)
            {
                string shongwai = ReadValue("通道设置", string.Format(@"红外{0}", i + 1));
                if (shongwai.Contains("车速到位"))
                {
                    iSPHW = i;
                }
                if (shongwai.Contains("车速遥控"))
                {
                    iSPYK = i;
                }
                
                shongwai = ReadValue("通道设置", string.Format(@"红外定位时间{0}", i + 1));
                int.TryParse(shongwai, out ihongwaidwsj[i]);


                shongwai = ReadValue("通道设置", string.Format(@"红外是否取反{0}", i + 1));
                if (shongwai.Contains("是"))
                {
                    bhongwaiqf[i] = true;
                }
                else
                {
                    bhongwaiqf[i] = false;
                }
            }
            if (scshwyk)
            {
                iSPHW = iSPYK;
            }
            ///控制
            for (int i = 0; i < 8; i++)
            {

                string shongwai = ReadValue("通道设置", string.Format(@"控制{0}", i + 1));
                if (shongwai.Contains("车速举升升"))
                {
                    iSPJS1 = i;
                }
                if (shongwai.Contains("车速举升降"))
                {
                    iSPJS2 = i;
                }
            }
        }

        private delegate void FlushClient();//代理
        private void xianshi()
        {
            if (this.xinxixianshi.InvokeRequired)//等待异步
            {
                FlushClient fc = new FlushClient(xianshi);
                this.Invoke(fc);//通过代理调用刷新方法
            }
            else
            {
                this.xinxixianshi.Text = string.Format(@"{0}", xianshineirong);
            }
        }

        private void xianshichesu()
        {
            if (this.gauge_speed.InvokeRequired)//等待异步
            {
                FlushClient fc = new FlushClient(xianshichesu);
                this.Invoke(fc);//通过代理调用刷新方法
            }
            else
            {
                this.gauge_speed.Visible = true;
                this.digitalGauge1.DigitCount = fchesu.ToString("0.0").Length - 1 < 3 ? 3 : fchesu.ToString("0.0").Length - 1;
                this.digitalGauge1.Text = fchesu.ToString("0.0"); 
            }
        }

        protected void thisclose()
        {
            this.Invoke(new Action(this.Close));  //使用委托关闭该窗体
        }

        /// <summary>
        /// 红外信号判断是否到位 路数 是否取反 保持稳定时间
        /// </summary>
        /// <param name="sName"></param>
        public void WaitEvent(int lushu, bool bqufan, int stime)
        {
            DateTime dstart = DateTime.Now;
            bool firstzt = false;
            while (true)
            {
                Thread.Sleep(10);
                if (flowbass.IsCancle())
                {
                    return;
                }
                bool bzhuangtai =m_mainform.DAC.bDIData[lushu];
                if (bqufan)
                {
                    bzhuangtai = !bzhuangtai;
                }
                if (bzhuangtai)
                {
                    firstzt = true;
                    flowbass.LedWrite(flowbass.sPlate, "停车", 1);
                    if (DateTime.Now>dstart.AddMilliseconds(stime))
                    {
                        break;
                    }
                }
                else
                {
                    dstart = DateTime.Now;
                    if (firstzt)
                    {
                        flowbass.LedWrite(flowbass.sPlate, "未到位", 1);
                    }
                }
            }
        }
        bool bcswc = false;
        public void StratTest()
        {
            fchesu = 0;
            if (!flowbass.bJCCSB)
            {
                xianshineirong = string.Format(@"车速免检");
                xianshi();
                flowbass.LedWrite(flowbass.sPlate, xianshineirong, 1);
                //if (iSPHW > -1)//配置红外后才判断红外定位
                //{
                //    m_mainform.WaitEventMJ(iSPHW, bhongwaiqf[iSPHW], ihongwaidwsj[iSPHW]);
                //}

                return;
            }
            flowbass.UpdateLoginRecord(DateTime.Now.ToString(), "车速检测开始", flowbass.sDetectID);
            xianshineirong = string.Format(@"驶上车速台");
            xianshi();
            flowbass.LedWrite(flowbass.sPlate,xianshineirong,  1);

            // 红外定位
            if (iSPHW > -1)//配置红外后才判断红外定位
            {
                WaitEvent(iSPHW, bhongwaiqf[iSPHW], ihongwaidwsj[iSPHW]);
            }

            if (flowbass.IsCancle())
            {
                return;
            }

            //举升下降
            if (iSPJS1 > 0 || iSPJS2 > 0)//举升控制为1路控制时默认是设置在第一个。
            {
                m_mainform.DAC.LiftTwo(false, (short)(iSPJS1), (short)(iSPJS2 ));
            }
          
            
           
            xianshineirong = string.Format(@"稳定40km/h 3~5秒后按遥控");
            xianshi();
            flowbass.LedWrite("稳定40km/h", "3~5秒后按遥控", 1);
            //测量数据
            DateTime dstart = DateTime.Now;
            bcswc = false;
            while (true)
            {
                Thread.Sleep(10);
                if (flowbass.IsCancle())
                {
                    flowbass.LedWrite("检测取消", "请停车", 1);
                    while (true)
                    {
                        Thread.Sleep(10);
                        if (m_mainform.DAC.fTIData[iSLtdz] < 3)
                        {
                            break;
                        }
                    }
                    return;
                }
                if ((m_mainform.WaitEventCS(iSPYK, bhongwaiqf[iSPYK], ihongwaidwsj[iSPYK]) && iSPYK > -1) || bcswc)
                {
                    fchesu = m_mainform.DAC.getjsz("车速速度", m_mainform.DAC.fTIData[iSLtdz]);              
                    fchesu = (float)Math.Round(fchesu, 1);
                    xianshichesu();

                    xianshineirong = string.Format(@"车速检测完成");
                    xianshi();
                    break;
                }
               

            }

            flowbass.LedWrite("车速检测完成", "请减速", 1);
            Thread.Sleep(1000);

            bool bGood = true;
            if (fchesu < flowbass.STD_SPDOLO || fchesu > flowbass.STD_SPDOHI)
            {
                bGood = false;
            }

            flowbass.AddData(flowbass.sDetectID, "DET_SPEEDJL", "Detects_SJA", bGood ? 1 : 2);

            flowbass.AddData_Check(flowbass.sDetectID, "DET_SPEED", "Detects_SJA", fchesu.ToString("0.0"));
            
            //检测结束
            string jielun = "";
            jielun = string.Format(@"{0},{1},{2},{3}", "车速表指示误差(km/h)", fchesu.ToString("0.0"), "32.8～40.0", bGood ? "合格" : "不合格");
            flowbass.AddData(flowbass.sDetectID, "PD_SPEED", "PD_AJ", jielun);
            flowbass.LedWrite("车速 " + fchesu.ToString("0.0"), bGood ? "合格" : "不合格", 1);
            Thread.Sleep(xssj);

            while (true)
            {
                Thread.Sleep(100);
                if (m_mainform.DAC.fTIData[iSLtdz] < 3)
                {
                    break;
                }
            }
             //举升上升
            if (iSPJS1 > 0 || iSPJS2 > 0)//举升控制为1路控制时默认是设置在第一个。
            {
                m_mainform.DAC.LiftTwo(true, (short)(iSPJS1), (short)(iSPJS2));
            }
            if (!bGood)
            {
                flowbass.getbuhge(flowbass.sDetectID, "S1");
            }
            else
            {
                flowbass.sethege(flowbass.sDetectID, "S1");
            }

          flowbass.getProcessfinish(flowbass.sDetectID, "S1");
          flowbass.LedWrite("车速工位", "", 1);
          flowbass.UpdateLoginRecord(DateTime.Now.ToString(), "车速检测结束", flowbass.sDetectID);
          flowbass.Updatejcxhao(flowbass.objcarclass.jcxdh, flowbass.sDetectID);

        }

        public void Thread1()
        {
            try
            {
                StratTest();

                if (jcxjs)
                {
                    xianshineirong = "检测线完成";
                    flowbass.UpdateLoginRecord(DateTime.Now.ToString(), "检测线完成", flowbass.sDetectID);
                    flowbass.LedWrite(flowbass.sPlate, xianshineirong, 1);
                    Thread.Sleep(1000);
                }
                if (flowbass.LastProcessnew(int.Parse(flowbass.sDetectID)) && !flowbass.ifinish)
                {
                    //flowbass.objajlwbass.sendAJend(flowbass.jylsh, false);
                    flowbass.LedWrite("正在发送", "联网总结束", 1);
                    string slianwangfanhui = flowbass.objajlwbass.sendAJend(flowbass.jylsh, false, flowbass.bzj);
                    if (!(slianwangfanhui.Length > 0 && slianwangfanhui[0].ToString() == "1"))
                    {
                        flowbass.LedWrite("联网失败", slianwangfanhui, 1);
                    }
                    else
                    {
                        flowbass.LedWrite("发送完成", "", 1);
                        flowbass.UpdateLoginRecord(DateTime.Now.ToString(), "检测线完成", flowbass.sDetectID);
                    }
                    Thread.Sleep(2000);
                }

                flowbass.LedWrite(flowbass.sgongwei, "", 1);
                xianshineirong = flowbass.sgongwei;
                xianshi();
                end();

            }
            catch (Exception ex)
            {
                //错误日记 记录到当天日期下目录中
                if (!(ex is System.Threading.ThreadAbortException))
                {
                    flowbass.LedWrite(flowbass.sPlate, "异常,停止检测", 1);
                    m_mainform.baocunriji("车速", ex.Message.ToString());

                    m_mainform.SaveErrorLog("车速检测流程", ex.Message.ToString());
                }
            }
        }

        public int panel_Width;
        public int panel_Height;   

        private void timer1_Tick(object sender, EventArgs e)
        {
            try
            {
                if (flowbass.izhuangtai == 2)
                {
                    m_mainform.objyibiaobass.select(flowbass.sshebei);
                    m_mainform.bpanelshow = true;
                    m_mainform.showpanel();
                    flowbass.izhuangtai = 1;

                    flowbass.IsReadyForStart();
                    t1 = new Thread(new ThreadStart(Thread1));
                    t1.Start();
                }
                else
                {

                }
            }
            catch (Exception ex)
            {
                m_mainform.baocunriji("车速打开窗体失败", ex.Message.ToString());
                m_mainform.SaveErrorLog("车速打开窗体", ex.Message.ToString());//problem
            }
        }

        public void timerstart()
        {
            timer1.Enabled = true;
        }

        public void end()
        {            
            flowbass.izhuangtai = 0;
            flowbass.sendend("E", flowbass.sDetectID);
        }

        private void closeform()
        {
            if (this.InvokeRequired)//等待异步
            {
                FlushClient fc = new FlushClient(closeform);
                this.Invoke(fc);//通过代理调用刷新方法
            }
            else
            {
                this.Dispose();
                this.Close();
            }
        }

        private void 仪表设置ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            工位配置.SPsetting obj = new 工位配置.SPsetting();
            obj.ShowDialog();
        }

        private void timer2_Tick(object sender, EventArgs e)
        {
            try
            {
                m_mainform.sethongwai(toolStripLabel2, m_mainform.WaitEventZT(iSPHW, bhongwaiqf[iSPHW], ihongwaidwsj[iSPHW]));

            }
            catch
            { }
            try
            {
                if (cbjd)
                {
                    Thread.Sleep(10);
                    fchesu = m_mainform.DAC.getjsz("车速速度", m_mainform.DAC.fTIData[iSLtdz]);
                    xianshichesu();
                    flowbass.LedWrite("车速", string.Format("{0}", fchesu.ToString("0.0")), 1);
                }
            }
            catch { }
        }

        private void but_start_Click(object sender, EventArgs e)
        {
            start();
        }

        private void But_Remote_Click(object sender, EventArgs e)
        {
            bcswc = true;
        }

        private void But_Lift_Up_Click(object sender, EventArgs e)
        {
            m_mainform.DAC.LiftTwo(true, (short)(iSPJS1), (short)(iSPJS2));
        }

        private void But_Lift_Down_Click(object sender, EventArgs e)
        {
            m_mainform.DAC.LiftTwo(false, (short)(iSPJS1), (short)(iSPJS2));
        }

        private void 显示控件ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ShowControls(true);
            ShowButtons(true);
        }

        public void ShowControls(bool flag)
        {
            lblhongwai1.Visible = flag;
            label1.Visible = flag;
        }

        public void ShowButtons(bool flag)
        {
            but_start.Visible = flag;
            But_Lift_Up.Visible = flag;
            But_Lift_Down.Visible = flag;
            But_Remote.Visible = flag;
            but_tiaoling.Visible = flag;
        }

        private void 设备检定ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            xinxixianshi.Text = "正在检定";
            cbjd = true;
        }

        private void 取消检定ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            xinxixianshi.Text = "车速检测";
            cbjd = false;
            flowbass.LedWrite(flowbass.sgongwei, "", 1);
        }

        private void but_tiaoling_Click(object sender, EventArgs e)
        {
            m_mainform.DAC.tiaoling(1);
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            start();
        }

        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            m_mainform.DAC.LiftTwo(true, (short)(iSPJS1), (short)(iSPJS2));
        }

        private void toolStripButton3_Click(object sender, EventArgs e)
        {
            m_mainform.DAC.LiftTwo(false, (short)(iSPJS1), (short)(iSPJS2));
        }

        private void toolStripButton4_Click(object sender, EventArgs e)
        {
            bcswc = true;
        }

        private void toolStripButton5_Click(object sender, EventArgs e)
        {
            m_mainform.DAC.tiaoling(1);
        }

        private void TESTSP_Shown(object sender, EventArgs e)
        {
            try
            {
                float newx = (this.Width) / x;
                float newy = (this.Height) / y;
                setControls(newx, newy, this);

                ShowButtons(false);
                this.BackgroundImage = Image.FromFile(@"./ico/车速背景.jpg");
                this.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
            }
            catch (Exception ex)
            {
                m_mainform.baocunriji("车速Load失败", ex.Message.ToString());//problem
                m_mainform.SaveErrorLog("车速Load失败", ex.Message.ToString());//problem
            }
        }
    }
}
